package com.tim.app.ui.view;

import android.content.Context;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.TimeUtil;
import com.application.library.widget.roundimg.RoundedImageView;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.ActionStateMsg;
import com.tim.app.server.entry.Comment;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.ActionResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.selected.ArticleDetailActivity;
import com.tim.app.ui.activity.some_homepage.SomeoneHomepageActivity;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

/**
 * 评论详情的header
 */

public class CommentHeadView extends LinearLayout implements View.OnClickListener {

    public static final String TAG = "CommentHeadView";

    RoundedImageView rivAvatar;
    TextView tvUserName;
    TextView etvComment;
    TextView tvPriseNumber;
    TextView tvReply;
    TextView tvReplyTime;
    TextView tvDelete;
    LinearLayout llRepltCommentContainer;
    TextView tvReplyUserName;
    TextView tvReplyComment;
    TextView tvReplyCommentCount;

    private Comment comment;

    public CommentHeadView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        rivAvatar = (RoundedImageView) findViewById(R.id.rivAvatar);
        tvUserName = (TextView) findViewById(R.id.tvUserName);
        tvReply = (TextView) findViewById(R.id.tvReply);
        tvPriseNumber = (TextView) findViewById(R.id.tvPriseNumber);
        tvReplyTime = (TextView) findViewById(R.id.tvReplyTime);
        etvComment = (TextView) findViewById(R.id.etvComment);
        tvDelete = (TextView) findViewById(R.id.tvDelete);
        llRepltCommentContainer = (LinearLayout) findViewById(R.id.llRepltCommentContainer);
        tvReplyUserName = (TextView) findViewById(R.id.tvReplyUserName);
        tvReplyComment = (TextView) findViewById(R.id.tvReplyComment);
        tvReplyCommentCount = (TextView) findViewById(R.id.tvReplyCommentCount);

        rivAvatar.setOnClickListener(this);
        tvUserName.setOnClickListener(this);
        tvPriseNumber.setOnClickListener(this);
        tvDelete.setOnClickListener(this);
        tvReply.setOnClickListener(this);

        mHandler = new Handler();
        priseTask = new PriseTask();
    }

    /**
     * 刷新页面
     *
     * @param data
     */
    public void setData(final Comment data) {
        if (null == data)
            return;
        this.comment = data;

        if (null != data.getUserMsg()) {
            if (!TextUtils.isEmpty(data.getUserMsg().getImage())) {
                BitmapLoader.ins().loadImage(data.getUserMsg().getImage(), rivAvatar);
            } else {
                BitmapLoader.ins().loadImage("", rivAvatar);
            }
            if (!TextUtils.isEmpty(data.getUserMsg().getName())) {
                tvUserName.setText(data.getUserMsg().getName());
            } else {
                tvUserName.setText("");
            }
        } else {
            BitmapLoader.ins().loadImage("", rivAvatar);
            tvUserName.setText("");
        }
        if (!TextUtils.isEmpty(data.getContent())) {
            etvComment.setText(data.getContent());
        } else {
            etvComment.setText("");
        }
        if (null != data.getActionStateMsg() && null != data.getActionStateMsg().getAgreeState()) {
            tvPriseNumber.setSelected(true);
            initPrise = true;
            isPrise = true;
        } else {
            tvPriseNumber.setSelected(false);
        }
//        if (UserManager.ins().isLogin() && null != data.getUserMsg() && !TextUtils.isEmpty(data.getUserMsg().getUserId()) && data.getUserMsg().getUserId().equals(UserManager.ins().getUserId())) {
//            tvDelete.setVisibility(View.VISIBLE);
//        } else {
//            tvDelete.setVisibility(View.GONE);
//        }
        tvPriseNumber.setText(String.valueOf(data.getAgreeCount()));
        tvReplyTime.setText(TimeUtil.formatTimeRuleOne(getContext(), data.getCreateTime()));

    }

    boolean isPrise;
    boolean initPrise;
    Handler mHandler;
    PriseTask priseTask;

    /**
     * 赞任务
     */
    class PriseTask implements Runnable {

        @Override
        public void run() {
            if (initPrise != isPrise) {
                addPriseOrCancelPrise();
            }
        }
    }

    /**
     * 赞/取消赞
     */
    public void addPriseOrCancelPrise() {
        API_User.ins().addPrise(TAG, UserManager.ins().getUserId(), AppKey.TYPE_COMMENT, comment.getId(), AppKey.AGREE, comment.getUserMsg().getUserId(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    ActionResult result = new Gson().fromJson(resultValue, ActionResult.class);
                    if (null != result && null != result.getRes()) {
                        if (null == comment.getActionStateMsg()) {
                            comment.setActionStateMsg(new ActionStateMsg());
                        }
                        comment.getActionStateMsg().setAgreeState(result.getRes().getAction().getId());
                    }
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rivAvatar:
            case R.id.tvUserName:
                SomeoneHomepageActivity.start(getContext(), comment.getUserMsg(), false);
                break;
            case R.id.tvPriseNumber:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(getContext());
                    return;
                }
                if (null != comment.getUserMsg() && !TextUtils.isEmpty(comment.getUserMsg().getUserId()) && comment.getUserMsg().getUserId().equals(UserManager.ins().getUserId())) {
                    ToastUtil.showToast("不能对自己的评论进行点赞");
                    return;
                }
                isPrise = !isPrise;
                tvPriseNumber.setSelected(isPrise);
                if (isPrise) {
                    comment.setAgreeCount(comment.getAgreeCount() + 1);
                } else {
                    comment.setAgreeCount(comment.getAgreeCount() - 1);
                }
                tvPriseNumber.setText(String.valueOf(comment.getAgreeCount()));
                mHandler.removeCallbacks(priseTask);
                mHandler.postDelayed(priseTask, AppKey.CLICK_REPEAT_TIME);
                break;
            case R.id.tvDelete:
                deleteComment();
                break;
            case R.id.tvReply:
                EventManager.ins().sendEvent(EventTag.ON_SELECT_PEPLY_COMMENT, 0, 0, null);
                break;
        }
    }

    /**
     * 删除评论
     */
    private void deleteComment() {
        tvDelete.setEnabled(false);
        API_User.ins().deleteComment(ArticleDetailActivity.TAG, comment.getId(), comment.getType(), String.valueOf(comment.getTypeId()), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                tvDelete.setEnabled(true);
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    EventManager.ins().sendEvent(EventTag.ON_COMMENT_HEADER_DELETED, 0, 0, comment.getId());
                    ToastUtil.showToast("删除成功");
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }
}
